<template>
  <div class="admin-settings">
    <div class="page-header">
      <h1 class="page-title">管理员设置</h1>
    </div>

    <!-- 修改头像 -->
    <el-card class="section-card" shadow="always">
      <h2 class="section-title">修改头像</h2>
      <div class="avatar-container">
        <div class="avatar-preview">
          <img v-if="avatarUrl" :src="avatarUrl" alt="管理员头像" class="avatar-img" />
          <el-avatar v-else :size="100" icon="el-icon-user-solid" />
        </div>
        <el-upload
            class="avatar-uploader"
            :show-file-list="false"
            :before-upload="beforeAvatarUpload"
            :http-request="uploadAvatar"
        >
          <el-button type="primary" size="small" icon="el-icon-upload2">上传新头像</el-button>
        </el-upload>
      </div>
    </el-card>

    <!-- 修改用户名 -->
    <el-card class="section-card" shadow="always">
      <h2 class="section-title">修改用户名</h2>
      <el-form
          :model="usernameForm"
          :rules="usernameRules"
          ref="usernameForm"
          label-width="100px"
          class="settings-form"
      >
        <el-form-item label="新用户名" prop="newUsername">
          <el-input
              v-model="usernameForm.newUsername"
              placeholder="请输入新用户名"
              maxlength="20"
              show-word-limit
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitUsername" :loading="usernameLoading">
            提交修改
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 修改密码 -->
    <el-card class="section-card" shadow="always">
      <h2 class="section-title">修改密码</h2>
      <el-form
          :model="passwordForm"
          :rules="passwordRules"
          ref="passwordForm"
          label-width="100px"
          class="settings-form"
      >
        <el-form-item label="验证码" prop="verificationCode">
          <el-input
              v-model="passwordForm.verificationCode"
              placeholder="请输入验证码"
              maxlength="6"
          >
            <template #append>
              <el-button
                  @click="getVerificationCode"
                  :disabled="codeDisabled"
                  :loading="codeLoading"
              >
                {{ codeText }}
              </el-button>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input
              v-model="passwordForm.newPassword"
              type="password"
              placeholder="请输入新密码"
              show-password
              maxlength="20"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitPassword" :loading="passwordLoading">
            提交修改
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 验证码弹窗 -->
    <el-dialog
        title="验证码已发送"
        v-model="dialogVisible"
        width="400px"
        custom-class="custom-dialog"
        :before-close="handleClose"
        :close-on-click-modal="false"
    >
      <div class="dialog-content">
        <p>验证码已发送，请在 60 秒内输入。</p>
        <p class="code-text">验证码：<span>{{ resetCode }}</span></p>
        <el-progress
            :percentage="Math.round((dialogCountdown / 60) * 100)"
            :show-text="false"
            :stroke-width="6"
            color="#409EFF"
        />
        <p class="countdown-text">剩余时间：{{ dialogCountdown }} 秒</p>
      </div>
      <template #footer>
        <el-button type="primary" @click="dialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  data() {
    return {
      avatarUrl: '',
      usernameForm: {
        newUsername: '',
      },
      passwordForm: {
        verificationCode: '',
        newPassword: '',
      },
      usernameRules: {
        newUsername: [
          { required: true, message: '请输入新用户名', trigger: 'blur' },
          { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' },
          { pattern: /^[a-zA-Z0-9_]+$/, message: '用户名只能包含字母、数字和下划线', trigger: 'blur' },
        ],
      },
      passwordRules: {
        verificationCode: [
          { required: true, message: '请输入验证码', trigger: 'blur' },
          { len: 6, message: '验证码应为6位', trigger: 'blur' },
        ],
        newPassword: [
          { required: true, message: '请输入新密码', trigger: 'blur' },
          { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' },
          { pattern: /^(?=.*[a-zA-Z])(?=.*\d).+$/, message: '密码必须包含字母和数字', trigger: 'blur' },
        ],
      },
      codeDisabled: false,
      codeText: '获取验证码',
      countdown: 60,
      dialogVisible: false,
      dialogCountdown: 60,
      resetCode: '',
      usernameLoading: false,
      passwordLoading: false,
      codeLoading: false,
    };
  },
  computed: {
    adminInfo() {
      return (
          this.$store.state.adminInfo ||
          JSON.parse(sessionStorage.getItem('adminInfo')) || {
            username: 'currentAdmin',
            role: 'common',
          }
      );
    },
    isCollapsed() {
      return this.$parent.isCollapsed; // 从父组件 layout.vue 获取
    },
  },
  watch: {
    isCollapsed() {
      this.$nextTick(() => {
        this.adjustLayout();
      });
    },
  },
  mounted() {
    this.fetchCurrentAdminInfo();
    this.$nextTick(() => {
      this.adjustLayout();
    });
  },
  methods: {
    adjustLayout() {
      const content = this.$el.querySelector('.admin-settings');
      if (content) {
        content.style.width = this.isCollapsed ? 'calc(100% - 60px)' : 'calc(100% - 220px)';
      }
    },
    async fetchCurrentAdminInfo() {
      try {
        const token = sessionStorage.getItem('token');
        if (!token) {
          this.$message.error({ message: '未登录，请先登录', center: true });
          this.$router.push('/');
          return;
        }
        const username = encodeURIComponent(this.adminInfo.username);
        const role = this.adminInfo.role;

        const response = await axios.get(axios.defaults.baseURL+'/api/admin/getAdminByUsername', {
          headers: {
            Authorization: `Bearer ${token}`,
            Role: role,
            Username: username,
          },
          params: { username: this.adminInfo.username },
        });
        this.avatarUrl = response.data.avatarUrl || '';
      } catch (error) {
        this.handleError(error, '获取管理员信息失败');
      }
    },
    beforeAvatarUpload(file) {
      const isImage = file.type.startsWith('image/');
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isImage) {
        this.$message.error({ message: '上传文件必须是图片格式！', center: true });
        return false;
      }
      if (!isLt2M) {
        this.$message.error({ message: '图片大小不能超过 2MB！', center: true });
        return false;
      }
      return true;
    },
    async uploadAvatar(params) {
      const file = params.file;
      const formData = new FormData();
      formData.append('file', file);

      try {
        const token = sessionStorage.getItem('token');
        if (!token) {
          this.$message.error({ message: '未找到认证令牌，请重新登录', center: true });
          this.$router.push('/');
          return;
        }

        const response = await axios.post(axios.defaults.baseURL+'/api/admin/uploadAvatar', formData, {
          headers: {
            Authorization: `Bearer ${token}`,
            'Content-Type': 'multipart/form-data',
          },
        });
        this.avatarUrl = response.data.split('访问地址: ')[1];
        this.$message.success({ message: '头像上传成功', center: true });
        this.fetchCurrentAdminInfo();
      } catch (error) {
        this.handleError(error, '头像上传失败');
      }
    },
    async getVerificationCode() {
      try {
        this.codeLoading = true;
        const token = sessionStorage.getItem('token');
        if (!token) {
          this.$message.error({ message: '未找到认证令牌，请重新登录', center: true });
          this.$router.push('/');
          return;
        }

        const response = await axios.post(axios.defaults.baseURL+'/api/admin/sendAdminPasswordCode', null, {
          headers: {
            Authorization: `Bearer ${token}`,
          },
        });
        this.resetCode = response.data.split('验证码已生成: ')[1];
        this.dialogVisible = true;
        this.dialogCountdown = 60;
        this.$message.success({ message: '验证码已发送', center: true });

        this.codeDisabled = true;
        this.countdown = 60;
        this.codeText = `${this.countdown}s`;
        const buttonTimer = setInterval(() => {
          this.countdown--;
          this.codeText = `${this.countdown}s`;
          if (this.countdown <= 0) {
            clearInterval(buttonTimer);
            this.codeDisabled = false;
            this.codeText = '获取验证码';
          }
        }, 1000);

        const dialogTimer = setInterval(() => {
          this.dialogCountdown--;
          if (this.dialogCountdown <= 0) {
            clearInterval(dialogTimer);
            this.dialogVisible = false;
          }
        }, 1000);
      } catch (error) {
        this.handleError(error, '获取验证码失败');
      } finally {
        this.codeLoading = false;
      }
    },
    async submitUsername() {
      this.$refs.usernameForm.validate(async (valid) => {
        if (!valid) return;

        try {
          this.usernameLoading = true;
          const token = sessionStorage.getItem('token');
          if (!token) {
            this.$message.error({ message: '未找到认证令牌，请重新登录', center: true });
            this.$router.push('/');
            return;
          }

          const response = await axios.post(
              axios.defaults.baseURL+'/api/admin/updateCurrentUsername',
              `newUsername=${encodeURIComponent(this.usernameForm.newUsername)}`,
              {
                headers: {
                  Authorization: `Bearer ${token}`,
                  'Content-Type': 'application/x-www-form-urlencoded',
                },
              }
          );
          this.$message.success({ message: response.data.message, center: true });

          const newToken = response.data.token;
          sessionStorage.setItem('token', newToken);
          const newAdminInfo = { ...this.adminInfo, username: this.usernameForm.newUsername };
          sessionStorage.setItem('adminInfo', JSON.stringify(newAdminInfo));
          this.$store.commit('setAdminInfo', newAdminInfo);

          this.usernameForm.newUsername = '';
          this.fetchCurrentAdminInfo();
        } catch (error) {
          this.handleError(error, '修改用户名失败');
        } finally {
          this.usernameLoading = false;
        }
      });
    },
    async submitPassword() {
      this.$refs.passwordForm.validate(async (valid) => {
        if (!valid) return;

        try {
          this.passwordLoading = true;
          const token = sessionStorage.getItem('token');
          if (!token) {
            this.$message.error({ message: '未找到认证令牌，请重新登录', center: true });
            this.$router.push('/');
            return;
          }

          const response = await axios.post(
              axios.defaults.baseURL+'/api/admin/updateCurrentPassword',
              `verificationCode=${encodeURIComponent(
                  this.passwordForm.verificationCode
              )}&newPassword=${encodeURIComponent(this.passwordForm.newPassword)}`,
              {
                headers: {
                  Authorization: `Bearer ${token}`,
                  'Content-Type': 'application/x-www-form-urlencoded',
                },
              }
          );
          this.$message.success({ message: response.data, center: true });
          this.passwordForm.verificationCode = '';
          this.passwordForm.newPassword = '';

          sessionStorage.removeItem('token');
          sessionStorage.removeItem('adminInfo');
          this.$store.commit('setAdminInfo', null);
          this.$router.push('/');
        } catch (error) {
          this.handleError(error, '修改密码失败');
        } finally {
          this.passwordLoading = false;
        }
      });
    },
    handleClose(done) {
      this.$confirm('确定关闭验证码弹窗吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
          .then(() => {
            this.dialogVisible = false;
            done();
          })
          .catch(() => {});
    },
    handleError(error, defaultMessage) {
      if (error.response?.status === 401) {
        this.$message.error({ message: '认证失败，请重新登录', center: true });
        this.$router.push('/');
      } else {
        this.$message.error({
          message: error.response?.data?.message || error.message || defaultMessage,
          center: true,
        });
      }
    },
  },
};
</script>

<style scoped>
.admin-settings {
  padding: 24px;
  background: #f5f7fa;
  min-height: calc(100vh - 96px);
  width: 100%;
  transition: width 0.3s ease;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.section-card {
  margin-bottom: 24px;
  border-radius: 8px;
  background: #fff;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  padding: 20px;
}

.section-title {
  font-size: 18px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 16px;
}

.avatar-container {
  display: flex;
  align-items: center;
  gap: 20px;
}

.avatar-preview {
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-img {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  object-fit: cover;
  border: 2px solid #e5e7eb;
  transition: transform 0.3s;
}

.avatar-img:hover {
  transform: scale(1.05);
}

.avatar-uploader :deep(.el-upload) {
  display: inline-block;
}

.settings-form {
  max-width: 400px;
}

.settings-form :deep(.el-form-item__label) {
  color: #606266;
  font-weight: 500;
}

.settings-form :deep(.el-input__inner) {
  border-radius: 6px;
}

.el-button {
  border-radius: 6px;
  transition: all 0.3s;
}

.el-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.el-button[type="primary"] {
  background: #409eff;
  border-color: #409eff;
}

.custom-dialog {
  border-radius: 8px;
}

.dialog-content {
  padding: 0 20px;
}

.dialog-content p {
  margin-bottom: 12px;
  color: #606266;
}

.code-text span {
  font-weight: 600;
  color: #409eff;
}

.countdown-text {
  margin-top: 12px;
  color: #909399;
}

:deep(.el-dialog__header) {
  border-bottom: 1px solid #f0f0f0;
  padding-bottom: 15px;
  font-weight: 600;
  color: #303133;
}

:deep(.el-dialog__footer) {
  border-top: 1px solid #f0f0f0;
  padding-top: 15px;
}

@media (max-width: 768px) {
  .admin-settings {
    padding: 16px;
  }

  .section-card {
    padding: 16px;
  }

  .avatar-container {
    flex-direction: column;
    align-items: flex-start;
  }

  .settings-form {
    max-width: 100%;
  }
}
</style>